//
//  NewTodayEarningsViewController.m
//  NewPro
//
//  Created by RYX on 2019/4/23.
//  Copyright © 2019 何荧红. All rights reserved.
//

#import "NewTodayEarningsViewController.h"
#import "NewTodayEarningsTableHeaderView.h"
#import "JXCategoryView.h"
#import "TGJLViewController.h"
#import "TZJLViewController.h"
#import "JHJLViewController.h"
#import "TodayEarningsStore.h"
#import "TodayEarningsModel.h"
#import "TodayEarningsList.h"

@interface NewTodayEarningsViewController ()<JXCategoryViewDelegate,NewTodayEarningsTableHeaderViewDelegate>
{
    NSString *selectedDate;
}

@property (nonatomic, strong) JXCategoryTitleView *categoryView;
@property (nonatomic, strong) NSArray <NSString *> *titles;
@property (nonatomic,strong) NewTodayEarningsTableHeaderView *userHeaderView;
@end

@implementation NewTodayEarningsViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self getCurrentDate];
    
    [self setNavBarWithTitle:@"当日收益详情"];
    
    _titles = @[@"推广奖励", @"拓展奖励", @"激活奖励"];
    
    _userHeaderView = [[NewTodayEarningsTableHeaderView alloc] initWithFrame:CGRectMake(0, 0, ScreenWidth, JXTableHeaderViewHeight)];
    _userHeaderView.currentTimeLa.text = [NSString stringWithFormat:@"%ld年%ld月%ld日",(long)[TodayEarningsList sharedInstance].year,(long)[TodayEarningsList sharedInstance].month,(long)[TodayEarningsList sharedInstance].day];
    _userHeaderView.delegate = self;
    
    _categoryView = [[JXCategoryTitleView alloc] initWithFrame:CGRectMake(0, 0, [UIScreen mainScreen].bounds.size.width, JXheightForHeaderInSection)];
    self.categoryView.titles = self.titles;
    self.categoryView.titleFont = [UIFont systemFontOfSize:14];
    self.categoryView.backgroundColor = [UIColor whiteColor];
    self.categoryView.delegate = self;
    self.categoryView.titleSelectedColor = BLUECOLOR;
    self.categoryView.titleColor = [UIColor blackColor];
//    self.categoryView.titleColorGradientEnabled = YES;
//    self.categoryView.titleLabelZoomEnabled = YES;
//    self.categoryView.titleLabelZoomEnabled = YES;
    
    JXCategoryIndicatorLineView *lineView = [[JXCategoryIndicatorLineView alloc] init];
    lineView.indicatorLineViewColor = BLUECOLOR;
    lineView.indicatorLineWidth = 55;
    lineView.indicatorLineViewHeight = 1.5;
    self.categoryView.indicators = @[lineView];
    
    _pagerView = [self preferredPagingView];
    self.pagerView.mainTableView.gestureDelegate = self;
    [self.view addSubview:self.pagerView];
    
    [_pagerView mas_makeConstraints:^(MASConstraintMaker *make) {
        
        make.top.left.right.bottom.equalTo(self.view);        
    }];
    
    self.categoryView.contentScrollView = self.pagerView.listContainerView.collectionView;
    
    self.pagerView.mainTableView.backgroundColor = BASECOLOR;
    
    MJWeakSelf
    MJRefreshNormalHeader *mjheader = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        
        [weakSelf loadData];
        [weakSelf getAllPOS];
        
    }];
    mjheader.lastUpdatedTimeLabel.hidden = YES;
    
    self.pagerView.mainTableView.mj_header = mjheader;
    
    //导航栏隐藏的情况，处理扣边返回，下面的代码要加上
    [self.pagerView.listContainerView.collectionView.panGestureRecognizer requireGestureRecognizerToFail:self.navigationController.interactivePopGestureRecognizer];
    [self.pagerView.mainTableView.panGestureRecognizer requireGestureRecognizerToFail:self.navigationController.interactivePopGestureRecognizer];
    
    [self loadData];
    [self getAllPOS];
}

- (void)getCurrentDate{
    
    NSDate *now = [NSDate date];
    NSCalendar *calendar = [NSCalendar currentCalendar];
    NSUInteger unitFlags = NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitDay;
    NSDateComponents *dateComponent = [calendar components:unitFlags fromDate:now];
    
    [TodayEarningsList sharedInstance].year =(int) [dateComponent year];
    [TodayEarningsList sharedInstance].month = (int) [dateComponent month];
    [TodayEarningsList sharedInstance].day = (int) [dateComponent day];
    
}
- (void)loadData{
    
    NSString *cyear = [NSString stringWithFormat:@"%ld",(long)[TodayEarningsList sharedInstance].year];
    NSString *cmonth = [NSString stringWithFormat:@"%ld",(long)[TodayEarningsList sharedInstance].month];
    NSString *cday = [NSString stringWithFormat:@"%ld",(long)[TodayEarningsList sharedInstance].day];
    
    MJWeakSelf
    TodayEarningsStore *store = [[TodayEarningsStore alloc] init];
    [store getTodayEarningsHeaderInfoWithYear:cyear month:cmonth day:cday Success:^(TodayEarningsModel *model) {
        
        weakSelf.userHeaderView.model = model;
        [weakSelf.pagerView.mainTableView.mj_header endRefreshing];
        
    } Failure:^(NSError *error) {
       
        [weakSelf.pagerView.mainTableView.mj_header endRefreshing];
        [weakSelf showMBPError:[HttpTool handleError:error]];
    }];
    
    [[NSNotificationCenter defaultCenter] postNotificationName:@"TODAYEARNING" object:nil];

}
- (void)getAllPOS{
    WS(weakself);
    [[[TodayEarningsStore alloc] init] getAllPosWithPrams:@{} Success:^(NSArray *listArr) {
        weakself.userHeaderView.AllPOS = listArr;
    } Failure:^(NSError *error) {
        [weakself showMBPError:[HttpTool handleError:error]];
    }];
}
- (JXPagerView *)preferredPagingView {
    return [[JXPagerView alloc] initWithDelegate:self];
}

- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
    
    self.navigationController.interactivePopGestureRecognizer.enabled = (self.categoryView.selectedIndex == 0);
}

//- (void)viewDidLayoutSubviews {
//    [super viewDidLayoutSubviews];
//
//    self.pagerView.frame = CGRectMake(0, iPhoneX_Top, ScreenWidth, ScreenHeight);
//}

#pragma mark - JXPagerViewDelegate

- (UIView *)tableHeaderViewInPagerView:(JXPagerView *)pagerView {
    return self.userHeaderView;
}

- (NSUInteger)tableHeaderViewHeightInPagerView:(JXPagerView *)pagerView {
    return JXTableHeaderViewHeight;
}

- (NSUInteger)heightForPinSectionHeaderInPagerView:(JXPagerView *)pagerView {
    return JXheightForHeaderInSection;
}

- (UIView *)viewForPinSectionHeaderInPagerView:(JXPagerView *)pagerView {
    return self.categoryView;
}

- (NSInteger)numberOfListsInPagerView:(JXPagerView *)pagerView {
    //和categoryView的item数量一致
    return self.titles.count;
}

- (id<JXPagerViewListViewDelegate>)pagerView:(JXPagerView *)pagerView initListAtIndex:(NSInteger)index {

    if (index == 0) {
        
        TGJLViewController *VC = [[TGJLViewController alloc] init];
        return VC;
        
    }else if (index == 1){
        
        TZJLViewController *VC = [[TZJLViewController alloc] init];
        return VC;
        
    }else{
        
        JHJLViewController *VC = [[JHJLViewController alloc] init];
        return VC;
    }
}

#pragma mark - JXCategoryViewDelegate

- (void)categoryView:(JXCategoryBaseView *)categoryView didSelectedItemAtIndex:(NSInteger)index {
    self.navigationController.interactivePopGestureRecognizer.enabled = (index == 0);
}

- (void)categoryView:(JXCategoryBaseView *)categoryView didClickedItemContentScrollViewTransitionToIndex:(NSInteger)index {
    //请务必实现该方法
    //因为底层触发列表加载是在代理方法：`- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath`回调里面
    //所以，如果当前有5个item，当前在第1个，用于点击了第5个。categoryView默认是通过设置contentOffset.x滚动到指定的位置，这个时候有个问题，就会触发中间2、3、4的cellForItemAtIndexPath方法。
    //如此一来就丧失了延迟加载的功能
    //所以，如果你想规避这样的情况发生，那么务必按照这里的方法处理滚动。
    [self.pagerView.listContainerView.collectionView scrollToItemAtIndexPath:[NSIndexPath indexPathForItem:index inSection:0] atScrollPosition:UICollectionViewScrollPositionCenteredHorizontally animated:NO];
    
    //如果你想相邻的两个item切换时，通过有动画滚动实现。未相邻的两个item直接切换，可以用下面这段代码
    /*
     NSInteger diffIndex = labs(categoryView.selectedIndex - index);
     if (diffIndex > 1) {
     [self.pagerView.listContainerView.collectionView scrollToItemAtIndexPath:[NSIndexPath indexPathForItem:index inSection:0] atScrollPosition:UICollectionViewScrollPositionCenteredHorizontally animated:NO];
     }else {
     [self.pagerView.listContainerView.collectionView scrollToItemAtIndexPath:[NSIndexPath indexPathForItem:index inSection:0] atScrollPosition:UICollectionViewScrollPositionCenteredHorizontally animated:YES];
     }
     */
}

#pragma mark - JXPagerMainTableViewGestureDelegate

- (BOOL)mainTableViewGestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldRecognizeSimultaneouslyWithGestureRecognizer:(UIGestureRecognizer *)otherGestureRecognizer {
    //禁止categoryView左右滑动的时候，上下和左右都可以滚动
    if (otherGestureRecognizer == self.categoryView.collectionView.panGestureRecognizer) {
        return NO;
    }
    return [gestureRecognizer isKindOfClass:[UIPanGestureRecognizer class]] && [otherGestureRecognizer isKindOfClass:[UIPanGestureRecognizer class]];
}


#pragma mark - NewTodayEarningsTableHeaderViewDelegate
- (void)onCalendarBtn{
    
    NSDate *minDate = [NSDate setYear:1978 month:3 day:12];
    NSDate *maxDate = [NSDate date];
    
    [BRDatePickerView showDatePickerWithTitle:@"选择日期" dateType:BRDatePickerModeYMD defaultSelValue:selectedDate minDate:minDate maxDate:maxDate isAutoSelect:YES themeColor:nil resultBlock:^(NSString *selectValue) {
        
        self->selectedDate = selectValue;
        
        NSArray *listArr = [selectValue componentsSeparatedByString:@"-"];
        self.userHeaderView.currentTimeLa.text = [NSString stringWithFormat:@"%@年%@月%@日",listArr[0],listArr[1],listArr[2]];
        [TodayEarningsList sharedInstance].year = [listArr[0] integerValue];
        [TodayEarningsList sharedInstance].month = [listArr[1] integerValue];
        [TodayEarningsList sharedInstance].day = [listArr[2] integerValue];
        
    } cancelBlock:^{
        
        
    }];
}

- (void)onSearchBtn{
    
    [self.pagerView.mainTableView.mj_header beginRefreshing];
}
@end
